<template>
  <main-content title="优惠券领取明细">
    <template #search-bar>
      <SearchBar inline>
        <template #normal>
          <el-form-item label="优惠券ID">
            <el-input
              v-model="searchForm.couponDefineId"
              clearable
              placeholder="请输入优惠券ID"
            />
          </el-form-item>
          <el-form-item label="用户ID">
            <el-input
              v-model="searchForm.userId"
              clearable
              placeholder="请输入用户ID"
            />
          </el-form-item>
          <el-form-item label="批次ID">
            <el-input
              v-model="searchForm.couponBatchId"
              clearable
              placeholder="请输入批次ID"
            />
          </el-form-item>

          <el-form-item label="领取时间">
            <el-date-picker
              v-model="receiveTimeModel"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
        </template>
        <template #toolbar>
          <el-form-item>
            <el-button
              type="primary"
              @click="research"
            >
              查询
            </el-button>
            <el-button
              type="primary"
              @click="exportClaimDetail"
            >
              导出
            </el-button>
          </el-form-item>
        </template>
      </SearchBar>
    </template>

    <div class="statistics">
      领取
      <span class="highlight">{{ couponClaimStatics?.receiveNum }}</span>
      张，使用
      <span class="highlight">{{ couponClaimStatics?.usedNum }}</span>
      张
    </div>

    <LayoutTable
      ref="tableRef"
      url="merchant/coupon/pageReceiveCouponDetail"
      :param="searchForm"
      :data="tableData"
    >
      <el-table-column
        label="优惠券ID"
        width="100"
        prop="couponDefineId"
      />
      <el-table-column
        label="优惠券名称"
        width="250"
        prop="couponName"
      />
      <el-table-column
        label="优惠券类型"
        width="120"
      >
        <template #default="props">
          {{ getCouponTypeName(props.row.couponType) }}
        </template>
      </el-table-column>
      <el-table-column
        label="批次ID"
        width="100"
        prop="couponBatchId"
      />
      <el-table-column
        label="批次名称"
        width="200"
        prop="couponBatchName"
      />
      <el-table-column
        label="用户ID"
        width="200"
        prop="userId"
      />
      <el-table-column
        label="手机号"
        width="180"
        prop="userPhone"
      />
      <el-table-column
        label="领取时间"
        width="210"
      >
        <template #default="props">
          <div
            class="claim-time-range"
            :class="{'outof-claim-time-range': checkOutofTimeRange(props.row)}"
          >
            <div>{{ formatTime(props.row.receiveTime) }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="使用时间"
        width="180"
      >
        <template #default="{row}">
          {{ formatTime(row.useTime) }}
        </template>
      </el-table-column>
    </LayoutTable>
  </main-content>

  <export-data
    v-model:show-dialog="isShowExportDialog"
    :export-type="exportForm.beanName"
    :title="exportForm.title"
  />
</template>

<script setup lang="ts">
import type { ICouponManageRow } from "@/api/modules/marketingTool";
import moment from "moment";
import { useCouponType } from "@/views/marketingTool/compositions/useCouponType"
import { getCouponClaimStatics, deleteCouponDefine, updateCouponDefineStatus } from "@/api/marketingTool"


const router = useRouter()
const { getCouponTypeName } = useCouponType()

const searchForm = ref({
  couponDefineName: "",
  couponType: "",
  status: "",
  receiveStartTime: "",
  receiveEndTime: "",
})

const receiveTimeModel = ref([])
watch(receiveTimeModel, (value) => {
  if (!value) {
    searchForm.value.receiveStartTime = ''
    searchForm.value.receiveEndTime = ''
    return
  }

  searchForm.value.receiveStartTime = moment(value[0]).valueOf()
  searchForm.value.receiveEndTime = moment(value[1]).valueOf()
})

watch(() => searchForm, () => {
  _getCouponClaimStatics()
}, { deep: true })

const tableRef = ref();
const tableData = ref([ { a: 1 } ]);

const research = () => {
  tableRef.value.research();
}

const currentRow = ref();

// 新增
const toCreate = (row: ICouponManageRow) => {
  console.log("新增！！！")
  router.push({
    path: 'coupon_manage/create'
  })
}

// 优惠券状态切换
const handleStatusChange: (row: ICouponManageRow) => Promise<boolean> = (row) => {
  console.log("状态切换！！！")
  return new Promise<boolean>((resolve) => {
    updateCouponDefineStatus({ 
      id: row.id,
      status: row.status === 1 ? 0 : 1 // 是否禁用 1 禁用 0 启用
    })
      .then(rs => {
        if (rs.code === 200) {
          resolve(true)
        } else {
          resolve(false)
        }
      })
  }).catch(e => {
    console.log(e)
    return Promise.resolve(false)
  })
}

// 领取时间
const formatTime = (timestamp: number) => {
  return timestamp ? moment(timestamp).format("YYYY.MM.DD HH:mm:ss") : ''
}

const checkOutofTimeRange = (row: ICouponManageRow) => {
  const now = +new Date();
  return row.receiveStartTime < now || row.receiveEndTime > now 
}

// 编辑
const toEdit = (row: ICouponManageRow) => {
  console.log("编辑！！！")
  router.push({
    path: 'coupon_manage/edit',
    query: {
      id: row.id
    }
  })
}

// 复制
const copy = async (row: ICouponManageRow) => {
  console.log("复制！！！")
  router.push({
    path: 'coupon_manage/edit',
    query: {
      id: row.id,
      action: "copy"
    }
  })
}

// 更多
const handleCommand = (command: string, row: ICouponManageRow) => {
  switch (command) {
    // case "send_coupon_manually": sendCouponManually(row);break;
    case "export_claim_detail": exportClaimDetail(row);break;
    case "delete_coupon": deleteCoupon(row);break;
    default: console.log("command not found");
  }
}

// 手动发券
// const sendCouponManually = (row: ICouponManageRow) => {
//   console.log("手动发券")
// }

// 导出领取明细
const isShowExportDialog = ref(false);
const exportForm = ref({
  beanName: "couponUserDetailExport", // 固定值 
  title: ""
})
const exportClaimDetail = (row: ICouponManageRow) => {
  currentRow.value = row;
  exportForm.value.title = "优惠券领取明细";
  isShowExportDialog.value = true
}

// 删除
const deleteCoupon = (row: ICouponManageRow) => {
  ElMessageBox.confirm("确认删除？", "提示").then(async () => {
    const rs = await deleteCouponDefine({ id: row.id })
    if (rs.code === 200) {
      ElMessage.success("删除成功")
      research()
    }
  }).catch(() => {
    void 0
  })
}

const couponClaimStatics = ref()
const _getCouponClaimStatics = async () => {
  const rs = await getCouponClaimStatics(searchForm.value)
  if (rs.code === 200) {
    couponClaimStatics.value = rs.payload
  }
}

onMounted(() => {
  _getCouponClaimStatics()
})
  
</script>

<style scoped lang="scss">
.statistics {
  margin-bottom: 18px;
  font-size: 14px;
  color: #333;

  .highlight {
    font-size: 16px;
    color: var(--el-color-primary);
  }
}

.outof-claim-time-range {
  color: #999;
}
</style>